package com.qcby.mycommunity_003.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qcby.mycommunity_003.annotation.LogAnnotation;
import com.qcby.mycommunity_003.entity.User;
import com.qcby.mycommunity_003.entity.UserRole;
import com.qcby.mycommunity_003.form.UpdatePassowrdForm;
import com.qcby.mycommunity_003.form.UserForm;
import com.qcby.mycommunity_003.mapper.UserMapper;
import com.qcby.mycommunity_003.mapper.UserRoleMapper;
import com.qcby.mycommunity_003.service.MenuService;
import com.qcby.mycommunity_003.service.RoleService;
import com.qcby.mycommunity_003.service.UserRoleService;
import com.qcby.mycommunity_003.service.UserService;
import com.qcby.mycommunity_003.util.Result;
import com.qcby.mycommunity_003.vo.MenuRecordVO;
import com.qcby.mycommunity_003.vo.PageVo;
import com.qcby.mycommunity_003.vo.UserListVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author admin
 * @since 2024-03-23
 */
@RestController
@RequestMapping("/sys/user")
public class UserController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private UserRoleService user_roleService;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @GetMapping("/getRouters")
    public Result rounter(HttpSession httpSession){
        //1.data-获取当前的登录的用户信息，返回数据data
        User user =(User) httpSession.getAttribute("user");
        if(user==null){
            return Result.ok().put("meg","没有登录信息？");
        }
        //2.role-通过当前用户的id查询到身份 role封装
        String role = roleService.getRoleNameByUserId(user.getUserId());
        //3.routers-查询路由
        List<MenuRecordVO> routers = menuService.getMenusByUserId(user.getUserId());
        return Result.ok().put("data",user).put("roles",role).put("routers",routers);
    }

    /**
     * 修改用户密码，自己封装form类
     * @param updateForm
     * @param session
     * @return
     */
    @LogAnnotation("修改密码")
    @PutMapping("/updatePassword")
    public Result updatepassword(@RequestBody UpdatePassowrdForm updateForm,HttpSession session){
        //获取当前存的session中的user对象
        User user = (User) session.getAttribute("user");
//        比对session中的信息和输入的密码
        String password1 = SecureUtil.sha256( updateForm.getPassword());
        String password2 = user.getPassword();
        if(!password1.equals(password2)){
            Result.ok().put("status","passwordError");
        }
        //更新用户的密码,将form表单的数据加密，user封装
        user.setPassword(SecureUtil.sha256(updateForm.getNewPassword()));
        boolean b = userService.updateById(user);
        if(b){
            return Result.ok().put("status","success");
        }else{
          return Result.error("更新失败!!");
        }
    }
    @GetMapping("/list")
    public Result UserList(UserListVo userListVo){
        PageVo pageVo=userService.userList(userListVo);
        return Result.ok().put("data",pageVo);
    }
    @LogAnnotation("添加用户")
    @PostMapping("/add")
    public Result add(@RequestBody UserForm userForm){
        //先往用户表里面插入再往用户角色表里插入，因为userid不是通过form传递的而是通过自增生成的
        //往用户表插入
        User u=new User();
        BeanUtils.copyProperties(userForm,u);
        //对用户密码加密
        String passoord1=SecureUtil.sha256(u.getPassword());
        u.setPassword(passoord1);
        boolean save1 = userService.save(u);
        if(!save1){
            return Result.error("插入用户失败");
        }
       //往用户角色表插入
        UserRole ur=new UserRole();
        ur.setRoleId(userForm.getRoleId());
        ur.setUserId(u.getUserId());
        boolean save = user_roleService.save(ur);
        if(!save){
            return Result.error("插入用户角色表失败");
        }
        return Result.ok();
    }
    @GetMapping("/info/{id}")
    public Result getOneById(@PathVariable Integer id){
    UserForm u=new UserForm();
    User user = userService.getById(id);
    BeanUtils.copyProperties(user,u);
    QueryWrapper<UserRole> queryWrapper=new QueryWrapper<>();
    queryWrapper.eq("user_id",user.getUserId());
    UserRole one = user_roleService.getOne(queryWrapper);
    u.setRoleId(one.getRoleId());
    return Result.ok().put("data",u);
    }
    @LogAnnotation("编辑用户信息")
    @PutMapping("/edit")
    public Result updateUser(@RequestBody UserForm userForm){
        //修改用户角色表
        UserRole ur=new UserRole();
        ur.setUserId(userForm.getUserId());
        ur.setRoleId(userForm.getRoleId());
        QueryWrapper<UserRole> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("user_id",userForm.getUserId());
       user_roleService.update(ur,queryWrapper1);
        //修改用户表
        User user=new User();
        BeanUtils.copyProperties(userForm,user);
        //修改密码也要加密
        String passoord1=SecureUtil.sha256(user.getPassword());
        user.setPassword(passoord1);
        userService.updateById(user);
        return Result.ok();
    }
    @LogAnnotation("删除用户")
    @DeleteMapping("/del")
    public Result del(@RequestBody List<Integer> list){
        //删除用户角色表
        QueryWrapper<UserRole> ur_q=new QueryWrapper<>();
        ur_q.in(!list.isEmpty(),"user_id",list);
        user_roleService.remove(ur_q);
        //删除用户表
        QueryWrapper<User> u_q=new QueryWrapper<>();
        u_q.in(!list.isEmpty(),"user_id",list);
        userMapper.deleteBatchIds(list);
        return Result.ok();
    }
}

